import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://likede2-admin.itheima.net/likede/',
  timeout: 5000 // request timeout
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 获取user模块下的 token 全局数据
    if (!config.headers.Authorization && store.state.user.token) {
      config.headers.Authorization = `${store.state.user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // console.log(response.data)
    const { msg, success } = response.data
    // 接口响应成功
    if (response.data.msg) {
      if (success) {
        Message.success(msg)
        console.log(success)
        Promise.resolve(response)
        return response
      } else {
        Message.error(msg)
        // 抛出错误
        // return Promise.reject(msg)
      }
    } else {
      return response
    }
  },
  error => {
    // 当请求状态码为401，说明token请求过期，需要重新登录
    console.dir(error)
    if (error.response.status === 401) {
      store.commit('user/removeToken')
      router.push('/login')
      Message.error('用户登录过期，请重新登录')
    }
    if (error.response.status === 500) {
      Message.error(error.response.data)
    }
    // 接口响应失败
    return Promise.reject(error)
  }
)

export default request
